package com.genymobile.scrcpy.five.cmd;

import com.genymobile.scrcpy.five.inject.FiveInjector;

public class SleepCmd extends ICmd {

    public long sleepMs = 0;
    /**
     * 当这个不为0，即表示随机sleep，范围 [sleepMs, rangeEndSleepMs)
     */
    public long rangeEndSleepMs = 0;

    @Override
    public boolean run(FiveInjector injector) {
        try {
            long sleepTime = sleepMs;
            if (rangeEndSleepMs > 0) {
                if (rangeEndSleepMs > sleepMs) {
                    // 范围内随机sleep
                    long range = rangeEndSleepMs - sleepMs;
                    sleepTime = (long) (Math.random() * range + sleepMs);
                }
            }
//            System.out.println("sleep:" + sleepTime);
            Thread.sleep(sleepTime);
        } catch (Exception ignored) {}
        return true;
    }

    @Override
    public String toString() {
        return super.toString() + sleepMs;
    }

    @Override
    public SleepCmd parse(long timestampMs, String[] arr) {
        SleepCmd cmd = new SleepCmd();
        cmd.timestampMs = timestampMs;
        cmd.sleepMs = Long.parseLong(arr[0]);
        if (arr.length >= 2) {
            cmd.rangeEndSleepMs = Long.parseLong(arr[1]);
        }
        return cmd;
    }

    @Override
    String getCmdName() {
        return "sleep";
    }
}
